package zip;

import Util.CreateFileUtil;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * JDK java.util.zip Deflater/Inflater test
 */
public class JdkDeflateTest extends TestParent {
    @Param({"1", "2", "3", "4", "5", "6", "7", "8", "9"})
    public int LEVEL;

    @Param({"1", "2", "3", "4", "5", "6", "7", "8", "9"})
    public int CORE;
    static HashMap<Integer, byte[]> compressFile;
    static HashMap<Integer, byte[]> deCompressFile;
    static {
        compressFile = new HashMap<>();
        deCompressFile = new HashMap<>();
        for (int i = 1; i < 10; i++) {
            compressFile.put(i, CreateFileUtil.getBytesByFile("./test/test_"+i+".json"));
            deCompressFile.put(i,CreateFileUtil.getBytesByFile("./test/test_"+i+".Deflate_1"));
        }
    }

    @Benchmark
    public byte[] compress() {
        try {
            byte[] output = new byte[Integer.sum(compressFile.get(LEVEL).length + 10,
                    Double.valueOf(Math.ceil(compressFile.get(LEVEL).length * 0.25f)).intValue())];
            Deflater compresser = new Deflater(CORE);//压缩级别
            compresser.setInput(compressFile.get(LEVEL));
            compresser.finish();
            int compressedDataLength = compresser.deflate(output);
            compresser.end();
            byte[] out = Base64.getEncoder().encode(Arrays.copyOf(output, compressedDataLength));
            CreateFileUtil.bytes2File(out,"./test/","test_"+LEVEL+".Deflate_"+CORE);
            return out;
        } catch (Exception ignored) {
            return null;
        }
    }

    @Benchmark
    public byte[] decompress() throws IOException {

        Inflater inflater = new Inflater();
        inflater.setInput(Base64.getDecoder().decode(deCompressFile.get(LEVEL)));
        ByteArrayOutputStream baos = new ByteArrayOutputStream(Base64.getDecoder().decode(deCompressFile.get(LEVEL)).length);
        try {
            byte[] buff = new byte[1024];
            while (!inflater.finished()) {
                int count = inflater.inflate(buff);
                baos.write(buff, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.close();
        }
        inflater.end();
        byte[] output = baos.toByteArray();
        CreateFileUtil.bytes2File(output,"./test/","test_"+LEVEL+".Deflate.json");
        return output;

    }


}
